import { defineStore } from 'pinia'
import { login as userLogin, getUserInfo } from '../api/system/login'

export const useUserStore = defineStore(
  'user',
  {
    state: () => ({
      token: undefined,
      userInfo: null,
      isLogin: false
    }),

    getters: {
      isLogin() {
        return !!this.token
      },
    },

    actions: {
      setToken(token) {
        this.token = token
      },
      getToken() {
        return this.token
      },
      clearToken() {
        this.token = undefined
      },
      setInfo(partial) {
        this.userInfo = Object.assign({}, this.userInfo, partial)
      },
      resetInfo() {
        this.userInfo = {}
      },

      // Get user's information
      async info() {
        const res = await getUserInfo()
        console.log('用户信息', res)
        this.setInfo(res.data)
      },

      // Login
      async login(userData) {
        try {
          const res = await userLogin(userData)
          this.setToken(res.data.token)
          this.setInfo(res.data)
          this.isLogin = true
          uni.setStorageSync('isLoggedIn', true)
        } catch (err) {
          this.clearToken()
          throw err
        }
      },
      logout() {
        this.clearToken()
        this.resetInfo()
        this.isLogin = false
        uni.removeStorageSync('isLoggedIn')
        uni.reLaunch({ url: '/pages/login/index' })
      },
    },
    persist: {
      storage: { // 修改存储方式
        getItem: uni.getStorageSync,
        setItem: uni.setStorageSync
      },
      key: 'userInfo', // 本地存储key值
      // paths: ['userInfo', 'token'] // 指定持久化的数据，不写默认持久化整个state
    }
  },
)
